package com.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youdianda.common.CustomException;
import com.youdianda.common.PageResult;
import com.youdianda.common.R;
import com.youdianda.entity.YddLink;
import com.youdianda.service.YddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ydd_link")
@Slf4j
public class YddLinkController {
    @Autowired
    private YddLinkService yddLinkService;

    /**
     * 链接详情
     * 数据回显
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<YddLink> getById(@RequestParam Long id){
        log.info("id{}:",id);

        YddLink yddLink = yddLinkService.getById(id);
        return R.success(yddLink);
    }

    /**
     * 修改链接信息
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody YddLink yddLink){
        log.info(yddLink.toString());

        yddLinkService.updateById(yddLink);
        return R.success("数据修改成功");
    }

    /**
     * 删除链接
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R<String> delete(@RequestParam Long id){
        log.info("id{}:", id);
        //条件构造器
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        //构造条件进行查询
        queryWrapper.in(YddLink::getId,id);
        List<YddLink> yddLinkList = yddLinkService.list(queryWrapper);
        //进行遍历
        for (YddLink yddLink : yddLinkList) {
            if ("1".equals(yddLink.getDefaultData())){
                throw new CustomException("系统默认数据无法删除");
            }
        }
        yddLinkService.removeById(id);
        return R.success("数据删除成功");
    }

    /**
     * 添加链接
     * @param yddLink
     * @return
     */
    @PostMapping("add")
    public R<String> save(@RequestBody YddLink yddLink){
        log.info(yddLink.toString());

        yddLinkService.save(yddLink);
        return R.success("数据添加成功");
    }

    /**
     * 分页查询数据
     * @param type
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R page(String type,int page,int limit){
        //分页构造器
        Page<YddLink> pageInfo = new Page<>();
        //条件构造器
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        //构造条件
        queryWrapper.like(StringUtils.isNotEmpty(type),YddLink::getType,type);
        //构造排序条件
        queryWrapper.orderByDesc(YddLink::getId);
        yddLinkService.page(pageInfo,queryWrapper);

        //将数据封装为pageResult
        PageResult pageResult = PageResult.getResult(pageInfo);
        return R.success(pageResult);
    }



}
